package avicit.bdp.dms.tdm.rest;

import avicit.bdp.core.constant.Constants;
import avicit.bdp.dms.tdm.dto.AssetCatalogAuthDTO;
import avicit.bdp.dms.tdm.service.AssetCatalogAuthService;
import avicit.platform6.api.system.ConvertColumnClient;
import avicit.platform6.api.sysuser.dto.SysOrg;
import avicit.platform6.commons.utils.BusinessUtil;
import avicit.platform6.commons.utils.JsonHelper;
import avicit.platform6.commons.utils.StringUtils;
import avicit.platform6.core.context.ThreadContextHelper;
import avicit.platform6.core.rest.msg.QueryReqBean;
import avicit.platform6.core.rest.msg.QueryRespBean;
import avicit.platform6.core.rest.msg.ResponseMsg;
import com.fasterxml.jackson.core.type.TypeReference;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/** 数据资产目录授权Rest */
@RestController
@Api(tags = "数据资产目录授权")
@RequestMapping("/api/bdp/dms/catalog/auth")
public class AssetCatalogAuthRest {

  @Autowired private AssetCatalogAuthService assetCatalogAuthService;

  @Autowired private ConvertColumnClient convertColumnClient;

  /** 获取所有的一级单位 */
  @PostMapping("/get-all-first-company/v1")
  @ApiOperation(value = "获取所有的一级单位")
  public ResponseMsg<List<SysOrg>> getAllFirstCompany(
      @ApiParam(value = "查询条件名称", name = "orgName") @RequestBody SysOrg dto) {
    ResponseMsg<List<SysOrg>> responseMsg = new ResponseMsg<>();
    responseMsg.setResponseBody(assetCatalogAuthService.getAllDept(dto));
    return responseMsg;
  }

  /**
   * 按条件分页查询
   *
   * @param queryReqBean 查询条件
   */
  @PostMapping("/search-by-page/v1")
  @ApiOperation(value = "按条件分页查询")
  public ResponseMsg<QueryRespBean<AssetCatalogAuthDTO>> searchByPage(
      @ApiParam(value = "查询条件", name = "queryReqBean") @RequestBody
          QueryReqBean<AssetCatalogAuthDTO> queryReqBean) {
    ResponseMsg<QueryRespBean<AssetCatalogAuthDTO>> responseMsg = new ResponseMsg<>();
    if (StringUtils.isNotEmpty(queryReqBean.getSidx())
        && StringUtils.isNotEmpty(queryReqBean.getSord())) {
      String sordExp =
          BusinessUtil.getSortExpColumnName(
              queryReqBean.getSidx(), queryReqBean.getSord(), AssetCatalogAuthDTO.class);
      if (StringUtils.isNotEmpty(sordExp)) {
        queryReqBean.setSortExp(sordExp);
      }
    }
    if (StringUtils.isNotEmpty(queryReqBean.getKeyWord())) {
      DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
      AssetCatalogAuthDTO searchKeyWordParam =
          JsonHelper.getInstance()
              .readValue(
                  queryReqBean.getKeyWord(),
                  dateFormat,
                  new TypeReference<AssetCatalogAuthDTO>() {});
      queryReqBean.setSearchParams(searchKeyWordParam);
    }
    // 文档密级
    String wordSecret = ThreadContextHelper.getWordSecret();
    QueryRespBean<AssetCatalogAuthDTO> result =
        assetCatalogAuthService.searchByPage(
            queryReqBean, ThreadContextHelper.getOrgId(), wordSecret, queryReqBean.getSortExp());
    valueConvert(result.getResult());
    responseMsg.setResponseBody(result);
    return responseMsg;
  }

  /**
   * 按条件不分页查询
   *
   * @param orgIds 组织ID串
   */
  @PostMapping("/search-data/v1")
  @ApiOperation(value = "按条件不分页查询")
  public ResponseMsg<List<AssetCatalogAuthDTO>> search(
      @RequestParam(value = "orgIds") String orgIds) {
    ResponseMsg<List<AssetCatalogAuthDTO>> responseMsg = new ResponseMsg<>();
    List<AssetCatalogAuthDTO> result = assetCatalogAuthService.searchListByOrgIds(orgIds);
    responseMsg.setResponseBody(result);
    return responseMsg;
  }

  /**
   * 按条件不分页查询
   *
   * @param queryReqBean 查询条件
   */
  @PostMapping("/search/v1")
  @ApiOperation(value = "按条件不分页查询")
  public ResponseMsg<List<AssetCatalogAuthDTO>> search(
      @ApiParam(value = "查询条件", name = "queryReqBean") @RequestBody
          QueryReqBean<AssetCatalogAuthDTO> queryReqBean) {
    ResponseMsg<List<AssetCatalogAuthDTO>> responseMsg = new ResponseMsg<>();
    List<AssetCatalogAuthDTO> result = assetCatalogAuthService.searchList(queryReqBean);
    valueConvert(result);
    responseMsg.setResponseBody(result);
    return responseMsg;
  }

  /**
   * 通过主键查询单条记录
   *
   * @param id 主键id
   */
  @GetMapping("/get/{id}/v1")
  @ApiOperation(value = "通过主键查询单条记录")
  public ResponseMsg<AssetCatalogAuthDTO> get(
      @ApiParam(value = "主键id", name = "id") @PathVariable("id") String id) {
    ResponseMsg<AssetCatalogAuthDTO> responseMsg = new ResponseMsg<>();
    AssetCatalogAuthDTO dto = assetCatalogAuthService.queryByPrimaryKey(id);
    if (dto != null) {
      valueConvert(Collections.singletonList(dto));
    }
    responseMsg.setResponseBody(dto);
    return responseMsg;
  }

  /**
   * 修改部分对象字段
   *
   * @param dto 修改对象
   */
  @PutMapping("/update-sensitive/v1")
  @ApiOperation(value = "修改部分对象字段")
  public ResponseMsg<Integer> updateSensitive(@RequestBody AssetCatalogAuthDTO dto) {
    ResponseMsg<Integer> responseMsg = new ResponseMsg<>();
    responseMsg.setResponseBody(assetCatalogAuthService.updateSensitive(dto));
    return responseMsg;
  }

  /** 修改全部对象字段 */
  @PutMapping("/update-all/v1")
  @ApiOperation(value = "修改全部对象字段")
  public ResponseMsg<Integer> updateAll(@RequestBody AssetCatalogAuthDTO dto) {
    ResponseMsg<Integer> responseMsg = new ResponseMsg<>();
    responseMsg.setResponseBody(assetCatalogAuthService.updateAll(dto));
    return responseMsg;
  }

  /**
   * 保存对象
   *
   * @param dto 保存对象
   */
  @PostMapping("/save/v1")
  @ApiOperation(value = "新增对象")
  public ResponseMsg<String> save(@RequestBody AssetCatalogAuthDTO dto) {
    ResponseMsg<String> responseMsg = new ResponseMsg<>();
    if (StringUtils.isEmpty(dto.getId())) {
      dto.setOrgIdentity(ThreadContextHelper.getOrgId());
      responseMsg.setResponseBody(assetCatalogAuthService.insert(dto));
    } else {
      responseMsg.setResponseBody(String.valueOf(assetCatalogAuthService.updateAll(dto)));
    }
    return responseMsg;
  }

  /**
   * 保存数据
   *
   * @param orgIds 组织id串
   * @param catalogIds 数据目录id串
   * @return Integer
   */
  @PostMapping("/save-data/v1")
  @ApiOperation(value = "保存数据")
  public ResponseMsg<Integer> saveData(
      @RequestParam(value = "orgIds") String orgIds,
      @RequestParam(value = "catalogIds") String catalogIds) {
    ResponseMsg<Integer> responseMsg = new ResponseMsg<>();
    responseMsg.setResponseBody(assetCatalogAuthService.authCatalog(orgIds, catalogIds));
    return responseMsg;
  }

  /**
   * 按主键单条删除
   *
   * @param id 主键id
   */
  @DeleteMapping("/delete-by-id/{id}/v1")
  @ApiOperation(value = "按主键单条删除")
  public ResponseMsg<Integer> deleteById(
      @ApiParam(value = "主键id", name = "id") @PathVariable("id") String id) {
    ResponseMsg<Integer> responseMsg = new ResponseMsg<>();
    responseMsg.setResponseBody(assetCatalogAuthService.deleteById(id));
    return responseMsg;
  }

  /**
   * 批量删除
   *
   * @param ids 逗号分隔的id串
   */
  @DeleteMapping("/delete-by-ids/{ids}/v1")
  @ApiOperation(value = "批量删除")
  public ResponseMsg<Integer> deleteByIds(
      @ApiParam(value = "逗号分隔的id串", name = "ids") @PathVariable("ids") String ids) {
    ResponseMsg<Integer> responseMsg = new ResponseMsg<>();
    responseMsg.setResponseBody(assetCatalogAuthService.deleteByIds(ids));
    return responseMsg;
  }

  /**
   * 通过平台API将字段值转换为名称，包括通用选择组件、通用代码
   *
   * @param list list
   */
  private void valueConvert(List<AssetCatalogAuthDTO> list) {
    // 循环组装请求数据
    Map<String, Set<String>> convertFormData = new HashMap<>();
    for (AssetCatalogAuthDTO dto : list) {
      BusinessUtil.createConvertSet(
          convertFormData, Constants.BDP_DATA_SECRET_LEVEL_KEY, dto.getSecretLevel());
    }
    if (convertFormData.size() > 0) {
      // 获取请求结果
      Map<String, Map<String, String>> convertResultData =
          convertColumnClient.replace(convertFormData);
      // 循环设置Alias或Name的值
      for (AssetCatalogAuthDTO dto : list) {
        dto.setSecretLevelName(
            BusinessUtil.convertFormat(
                convertResultData, Constants.BDP_DATA_SECRET_LEVEL_KEY, dto.getSecretLevel()));
      }
    }
  }
}
